<template>
  <div class="file-tools-container">
    <h1>文件处理工具集</h1>
    
    <div class="tabs">
      <button 
        v-for="tab in tabs" 
        :key="tab.id" 
        :class="{ active: currentTab === tab.id }"
        @click="currentTab = tab.id"
      >
        {{ tab.name }}
      </button>
    </div>

    <div class="tab-content">
      <!-- 批量重命名 -->
      <div v-if="currentTab === 'rename'" class="tool-form">
        <h2>批量重命名</h2>
        <form @submit.prevent="handleRename">
          <div class="form-group">
            <label for="renamePath">目录路径:</label>
            <div class="path-input-group">
              <input 
                type="text" 
                id="renamePath" 
                v-model="renameData.path"
                placeholder="输入要处理的目录路径"
                required
              >
              <input type="file" ref="renameDirInput" webkitdirectory style="display: none;" @change="handleDirectorySelect('rename')">
              <button type="button" class="browse-btn" @click="browseDirectory('rename')">浏览...</button>
            </div>
          </div>
          
          <div class="form-group">
            <label for="renamePattern">匹配模式:</label>
            <input 
              type="text" 
              id="renamePattern" 
              v-model="renameData.pattern"
              placeholder="输入要匹配的文本或正则表达式"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="renameReplacement">替换内容:</label>
            <input 
              type="text" 
              id="renameReplacement" 
              v-model="renameData.replacement"
              placeholder="输入替换的文本"
              required
            >
          </div>
          
          <div class="form-group checkbox-group">
            <input 
              type="checkbox" 
              id="renameRecursive" 
              v-model="renameData.recursive"
            >
            <label for="renameRecursive">递归处理子目录</label>
          </div>
          
          <button type="submit" class="submit-btn">执行重命名</button>
        </form>
      </div>

      <!-- 内容替换 -->
      <div v-if="currentTab === 'replace'" class="tool-form">
        <h2>内容替换</h2>
        <form @submit.prevent="handleReplace">
          <div class="form-group">
            <label for="replacePath">目录路径:</label>
            <div class="path-input-group">
              <input 
                type="text" 
                id="replacePath" 
                v-model="replaceData.path"
                placeholder="输入要处理的目录路径"
                required
              >
              <input type="file" ref="replaceDirInput" webkitdirectory style="display: none;" @change="handleDirectorySelect('replace')">
              <button type="button" class="browse-btn" @click="browseDirectory('replace')">浏览...</button>
            </div>
          </div>
          
          <div class="form-group">
            <label for="searchText">查找内容:</label>
            <input 
              type="text" 
              id="searchText" 
              v-model="replaceData.searchText"
              placeholder="输入要查找的文本"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="replaceText">替换内容:</label>
            <input 
              type="text" 
              id="replaceText" 
              v-model="replaceData.replaceText"
              placeholder="输入替换的文本"
            >
          </div>
          
          <div class="form-group">
            <label for="fileExtensions">文件扩展名 (多个用逗号分隔):</label>
            <input 
              type="text" 
              id="fileExtensions" 
              v-model="replaceData.fileExtensions"
              placeholder="如: txt,js,html (留空则处理所有文件)"
            >
          </div>
          
          <div class="form-group checkbox-group">
            <input 
              type="checkbox" 
              id="replaceRecursive" 
              v-model="replaceData.recursive"
            >
            <label for="replaceRecursive">递归处理子目录</label>
          </div>
          
          <button type="submit" class="submit-btn">执行替换</button>
        </form>
      </div>

      <!-- 目录统计 -->
      <div v-if="currentTab === 'stats'" class="tool-form">
        <h2>目录统计</h2>
        <form @submit.prevent="handleStats">
          <div class="form-group">
            <label for="statsPath">目录路径:</label>
            <div class="path-input-group">
              <input 
                type="text" 
                id="statsPath" 
                v-model="statsData.path"
                placeholder="输入要统计的目录路径"
                required
              >
              <input type="file" ref="statsDirInput" webkitdirectory style="display: none;" @change="handleDirectorySelect('stats')">
              <button type="button" class="browse-btn" @click="browseDirectory('stats')">浏览...</button>
            </div>
          </div>
          
          <div class="form-group checkbox-group">
            <input 
              type="checkbox" 
              id="statsRecursive" 
              v-model="statsData.recursive"
            >
            <label for="statsRecursive">递归统计子目录</label>
          </div>
          
          <button type="submit" class="submit-btn">执行统计</button>
        </form>

        <!-- 统计结果 -->
        <div v-if="statsResult" class="stats-result">
          <h3>统计结果</h3>
          <div class="stats-grid">
            <div class="stats-item">
              <span class="stats-label">总文件数:</span>
              <span class="stats-value">{{ statsResult.fileCount }}</span>
            </div>
            <div class="stats-item">
              <span class="stats-label">总目录数:</span>
              <span class="stats-value">{{ statsResult.directoryCount }}</span>
            </div>
            <div class="stats-item">
              <span class="stats-label">总大小:</span>
              <span class="stats-value">{{ formatSize(statsResult.totalSize) }}</span>
            </div>
            <div class="stats-item">
              <span class="stats-label">平均文件大小:</span>
              <span class="stats-value">{{ formatSize(statsResult.averageFileSize) }}</span>
            </div>
          </div>

          <!-- 文件类型分布 -->
          <div class="file-types" v-if="statsResult.fileTypes.length > 0">
            <h4>文件类型分布</h4>
            <table>
              <thead>
                <tr>
                  <th>文件类型</th>
                  <th>数量</th>
                  <th>占比</th>
                  <th>总大小</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="type in statsResult.fileTypes" :key="type.extension">
                  <td>{{ type.extension || '无扩展名' }}</td>
                  <td>{{ type.count }}</td>
                  <td>{{ (type.count / statsResult.fileCount * 100).toFixed(2) }}%</td>
                  <td>{{ formatSize(type.totalSize) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" :class="{ 'success-message': messageType === 'success', 'error-message': messageType === 'error' }" class="message-box">
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

// 标签页数据
const tabs = [
  { id: 'rename', name: '批量重命名' },
  { id: 'replace', name: '内容替换' },
  { id: 'stats', name: '目录统计' }
]

// 当前选中的标签页
const currentTab = ref('rename')

// 消息提示
const message = ref('')
const messageType = ref('')

// 批量重命名数据
const renameData = ref({
  path: '',
  pattern: '',
  replacement: '',
  recursive: false
})

// 内容替换数据
const replaceData = ref({
  path: '',
  searchText: '',
  replaceText: '',
  fileExtensions: '',
  recursive: false
})

// 目录统计数据
const statsData = ref({
  path: '',
  recursive: false
})

// 统计结果
const statsResult = ref(null)

// 目录选择引用
const renameDirInput = ref(null)
const replaceDirInput = ref(null)
const statsDirInput = ref(null)

// 显示消息提示
const showMessage = (text, type = 'info') => {
  message.value = text
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 5000)
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 处理批量重命名
const handleRename = async () => {
  try {
    // 调用后端API进行批量重命名
    // 将前端的path参数转换为后端需要的directory参数
    const requestData = {
      directory: renameData.value.path,
      pattern: renameData.value.pattern,
      replacement: renameData.value.replacement,
      recursive: renameData.value.recursive
    }
    const response = await axios.post('/api/rename-files', requestData)
    showMessage(response.data.message, 'success')
    console.log('批量重命名结果:', response.data.data)
  } catch (error) {
    showMessage('批量重命名失败: ' + (error.response?.data?.message || error.message), 'error')
  }
}

// 处理内容替换
const handleReplace = async () => {
  try {
    // 调用后端API进行内容替换
    // 将前端参数转换为后端需要的格式
    const requestData = {
      directory: replaceData.value.path,
      search: replaceData.value.searchText,
      replace: replaceData.value.replaceText,
      extensions: replaceData.value.fileExtensions,
      recursive: replaceData.value.recursive
    }
    const response = await axios.post('/api/replace-content', requestData)
    showMessage(response.data.message, 'success')
    console.log('内容替换结果:', response.data.data)
  } catch (error) {
    showMessage('内容替换失败: ' + (error.response?.data?.message || error.message), 'error')
  }
}

// 浏览目录
const browseDirectory = (type) => {
  if (type === 'rename') renameDirInput.value?.click()
  else if (type === 'replace') replaceDirInput.value?.click()
  else if (type === 'stats') statsDirInput.value?.click()
}

// 处理目录选择
const handleDirectorySelect = (type) => {
  let inputElement
  let dataRef
  
  if (type === 'rename') {
    inputElement = renameDirInput.value
    dataRef = renameData
  } else if (type === 'replace') {
    inputElement = replaceDirInput.value
    dataRef = replaceData
  } else if (type === 'stats') {
    inputElement = statsDirInput.value
    dataRef = statsData
  }
  
  if (inputElement && inputElement.files && inputElement.files.length > 0) {
    try {
      // 从文件路径中提取目录路径
      // 在Web环境中，出于安全考虑，我们只能获取到虚拟路径
      // 但在开发环境和某些特定环境中，可以使用webkitRelativePath
      const file = inputElement.files[0]
      if (file.webkitRelativePath) {
        // 这是一个目录
        const paths = file.webkitRelativePath.split('/')
        if (paths.length > 1) {
          // 在浏览器中，我们无法获取真实路径，只能模拟显示
          dataRef.value.path = `/${paths[0]}` // 显示为根目录下的选定目录
        }
      } else {
        // 这是一个文件
        // 在浏览器中无法获取完整文件路径，只能获取文件名
        // 所以我们简单地显示一个提示信息
        showMessage('浏览器安全限制，无法获取完整文件路径。请手动输入路径。', 'info')
      }
    } catch (error) {
      showMessage('选择目录失败: ' + error.message, 'error')
    }
    
    // 重置输入，以便再次选择同一目录
    inputElement.value = ''
  }
}

// 处理目录统计
const handleStats = async () => {
  try {
    // 调用后端API进行目录统计
    // 将前端的path参数转换为后端需要的directory参数
    const requestData = {
      directory: statsData.value.path,
      recursive: statsData.value.recursive
    }
    const response = await axios.post('/api/directory-stats', requestData)
    statsResult.value = response.data.data
    showMessage(response.data.message, 'success')
  } catch (error) {
    showMessage('目录统计失败: ' + (error.response?.data?.message || error.message), 'error')
  }
}
</script>

<style scoped>
.file-tools-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.file-tools-container h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
}

.tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  border-bottom: 2px solid #eee;
}

.tabs button {
  background: none;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  color: #666;
  transition: all 0.3s ease;
  position: relative;
}

.tabs button:hover {
  color: #42b883;
}

.tabs button.active {
  color: #42b883;
  font-weight: bold;
}

.tabs button.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #42b883;
}

.tool-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tool-form h2 {
  color: #42b883;
  margin-top: 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #555;
  font-weight: bold;
}

.form-group input[type="text"] {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.path-input-group {
  display: flex;
  gap: 10px;
}

.path-input-group input {
  flex: 1;
}

.browse-btn {
  background-color: #666;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  white-space: nowrap;
}

.browse-btn:hover {
  background-color: #555;
}

.checkbox-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.checkbox-group input[type="checkbox"] {
  width: auto;
}

.submit-btn {
  background-color: #42b883;
  color: white;
  border: none;
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #3aa876;
}

/* 统计结果样式 */
.stats-result {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #eee;
}

.stats-result h3 {
  color: #333;
  margin-top: 0;
  margin-bottom: 15px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.stats-label {
  color: #555;
  font-weight: bold;
}

.stats-value {
  color: #42b883;
  font-weight: bold;
}

/* 文件类型表格 */
.file-types {
  margin-top: 20px;
}

.file-types h4 {
  color: #333;
  margin-top: 0;
  margin-bottom: 15px;
}

.file-types table {
  width: 100%;
  border-collapse: collapse;
}

.file-types th,
.file-types td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.file-types th {
  background-color: #f5f5f5;
  color: #333;
  font-weight: bold;
}

.file-types tr:hover {
  background-color: #f9f9f9;
}

/* 消息提示框 */
.message-box {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  z-index: 1000;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.success-message {
  background-color: #42b883;
}

.error-message {
  background-color: #e74c3c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .file-tools-container {
    padding: 10px;
  }
  
  .tabs {
    flex-direction: column;
  }
  
  .tabs button {
    text-align: left;
  }
  
  .path-input-group {
    flex-direction: column;
  }
  
  .browse-btn {
    width: 100%;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>